<?php
/**
 * User: hjd-yao
 * Date: 2019/3/11
 * Time: 14:33
 */

namespace App\Http\Controllers\User;

use App\Helpers\Search;
use App\Helpers\SelfEncrypt;
use App\Helpers\SelfResponse;
use App\Http\Controllers\BackendController;
use App\Http\Controllers\User\Traits\AjaxUser;
use App\Http\Controllers\User\Traits\OneselfUser;
use App\Http\Requests\UserRequest;
use App\Models\Bonus\BonusRecordModel;
use App\Models\Manage\LogsAdminModel;
use App\Models\ManageAdminModel;
use App\Models\Shop\UserAchievementModel;
use App\Models\User\AccountCorrectModel;
use App\User\UserCenter;
use DC\BonusCenter\Services\ShoppingBonus;
use DC\UserCenter\Models\UserAuthModel;
use DC\UserCenter\Models\UserBaseModel;
use DC\UserCenter\Models\UserInfoModel;
use DC\UserCenter\Models\UserWalletModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends BackendController
{
    use AjaxUser,OneselfUser;
    public $userCenter;

    public function __construct()
    {
        $this->userCenter = new UserCenter();
    }

    /**
     * @title 会员列表
     * @param Request $request
     * @return View
     */
    public function activatedUsers(Request $request)
    {
//        $info=UserBaseModel::where('member_id',7)->first();
//        $api=new ShoppingBonus();
//        $api->money_baodan($info,3000);
        $search = Search::make($request)->bindModel(UserBaseModel::with(['referrer'=>function($query){
            $query->select(['member_id','user_number','user_phone','real_name','status','level']);
        },'wallet'])->has('auth'))
            ->input('info','编号/姓名/手机号','',['symbol'=>'like','field'=>['user_number','real_name']])
            ->select('level','级别',format_option((['-100'=>'全部会员']+config('shop.level'))),'-100')
//            ->time('activated_at','激活时间')
            ->bindSearchData();

        $model = $search->where();
        if($request->has('info')){
            $info = $request->input('info');
            $model = $model->where(function ($query) use ($info){
                $query->where('user_number','like','%'.$info.'%')
                    ->orWhere('real_name','like','%'.$info.'%')
                    ->orWhere('user_phone','like','%'.$info.'%');
            });
        }

       $list = $model->where('status','>',0)->orderBy('activated_at','desc')->paginate($this->getPerPageNum());

       return view('backend::user.activated_users',[
           'page_title' => '会员列表',
           'currencies'=>get_currency(),
           'list' => $list,
           'search_tpl'=>$search
       ]);
    }

    /**
     * @title 待激活
     * @param Request $request
     * @return View
     */
    public function unactivatedUsers(Request $request)
    {
        $search = Search::make($request)->bindModel(UserBaseModel::with([
            'referrer'=>function($query){
                    $query->select(['member_id','user_number','user_phone','real_name','status']);
                },
            'bdr'=>function($query){
                $query->select(['member_id','user_number','user_phone','real_name','status']);
            },
            'wallet'
            ])->has('auth'))
            ->input('info','编号/姓名/手机号','',['symbol'=>'like','field'=>['user_number','real_name']])
            ->select('level','级别',format_option((['-100'=>'全部会员']+config('shop.level'))),'-100')
            ->time('created_at','注册时间')
            ->bindSearchData();

        $model = $search->where();
        if($request->has('info')){
            $info = $request->input('info');
            $model = $model->where(function ($query) use ($info){
                $query->where('user_number','like','%'.$info.'%')
                    ->orWhere('real_name','like','%'.$info.'%')
                    ->orWhere('user_phone','like','%'.$info.'%');
            });
        }

        $list = $model->where('status',0)->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::user.unactivated_users',[
            'page_title'=>'免费会员',
            'list'=>$list,
            'currencies'=>get_currency(),
            'search_tpl'=>$search
        ]);
    }

    /**
     * @title 已冻结会员
     * @param Request $request
     * @return View
     */
    public function frozenUsers(Request $request)
    {
        $search = Search::make($request)->bindModel(UserBaseModel::with(['referrer'=>function($query){
            $query->select(['member_id','user_number','user_phone','real_name','status']);
        },'wallet'])->has('auth'))
            ->input('info','编号/姓名/手机号','',['symbol'=>'like','field'=>['user_number','real_name']])
            ->time('created_at','注册时间')
            ->bindSearchData();

        $model = $search->where();
        if($request->has('info')){
            $info = $request->input('info');
            $model = $model->where(function ($query) use ($info){
                $query->where('user_number','like','%'.$info.'%')
                    ->orWhere('real_name','like','%'.$info.'%')
                    ->orWhere('user_phone','like','%'.$info.'%');
            });
        }

        $list = $model->where('status',-1)->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::user.frozen_users',[
            'page_title' => '冻结会员',
            'list' => $list,
            'search_tpl'=>$search
        ]);
    }

    /**
     * @title 添加会员
     * @param UserRequest $request
     * @return JsonResponse
     */
    public function createUser(UserRequest $request)
    {
        if($request->isMethod('post')){
            $user_center = new UserCenter();
            if(!$user_center->registerByAdmin($request)){
                return SelfResponse::error($user_center->getErrorMsg('注册失败,请重新尝试'));
            }
            return SelfResponse::success('注册成功','b_User_createUser');
        }else{
            $default_referrer = UserBaseModel::init()->getDefaultReferrer();
            return view('backend::user.add_user',[
                'page_title'=>'添加会员',
                'default_referrer'=>$default_referrer
            ]);
        }
    }

    /**
     * @title 编辑会员信息
     * @param Request $request
     * @param $id
     * @param string $action
     * @return View
     */
    public function editUser(Request $request,$id,$action='base')
    {
        $info = UserBaseModel::find($id);
        if($request->isMethod('post')){
            $user_center = new UserCenter();
            $data = $request->post();
            if(!$user_center->edit($data,$id,$action)){
                return SelfResponse::error($user_center->getErrorMsg('修改失败,请重新尝试'));
            }
            return SelfResponse::success('修改成功',['b_User_infoUser',['id'=>$id]]);
        }else{
            return view('backend::user.edit_user',[
                'page_title'=>'编辑'.$info->real_name.'的资料',
                'info'=>$info
            ]);
        }
    }

    /**
     * @title 重置会员密码
     * @param Request $request
     * @param $id
     * @param string $action
     * @return SelfResponse|View
     */
    public function resetUserPwd(Request $request,$id,$action='login')
    {
        $info = UserBaseModel::find($id);
        if($request->isMethod('post')){
            if(!$info){
                return SelfResponse::error('会员信息不存在,请确认信息');
            }
            $admin = new ManageAdminModel();
            if(!$admin->checkSafePwd($request->post('my_safe_pwd'),$admin->getLoginId())){
                return SelfResponse::error('安全密码错误,请重新尝试');
            }
            $user_auth = new UserAuthModel();
            if($action == 'login'){// 修改登录密码
                $login_pwd = $request->post('login_pwd');
                if(!$user_auth->updateLoginPwd($login_pwd,$id)){
                    return SelfResponse::error($user_auth->getErrorMsg('密码修改失败'));
                }
                $title = '登录密码';
            }else{//修改安全密码
                $safe_pwd = $request->post('safe_pwd');
                if(!$user_auth->updateSafePwd($safe_pwd,$id)){
                    return SelfResponse::error($user_auth->getErrorMsg('密码修改失败'));
                }
                $title = '安全密码';
            }
            return SelfResponse::success($title.'修改成功',['b_User_infoUser',['id'=>$info->member_id]]);
        }else{
            return view('backend::user.reset_user_pwd',[
                'page_title'=>'重置'.$info->real_name.'的密码',
                'user_id'=>$info->member_id
            ]);
        }
    }

    /**
     * @title 激活会员
     * @param $id
     * @param Request $request
     * @return SelfResponse
     */
    public function activatedUser(Request $request,$id)
    {

        $user_center = new UserCenter();
        if($user_center->activatedByAdmin($id)){
            return SelfResponse::success('激活成功','b_User_activatedUsers');
        }
        return SelfResponse::error($user_center->getErrorMsg('激活失败,请稍后再试！'));
    }

    /**
     * @title 空单激活会员
     * @param $id
     * @param Request $request
     * @return SelfResponse
     */
    public function EmptyActivatedUser(Request $request,$id)
    {
        $user_center = new UserCenter();
        if($user_center->EmptyActivatedUser($id)){
            return SelfResponse::success('激活成功','b_User_activatedUsers');
        }
        return SelfResponse::error($user_center->getErrorMsg('激活失败,请稍后再试！'));
    }

    /**
     * @title 冻结会员
     * @param Request $request
     * @param $id
     * @return SelfResponse
     */
    public function freezeUser(Request $request,$id)
    {
        $user_center = new UserCenter();
        if($user_center->freeze($id,$request->input('freeze_cause','账号异常'))){
            return SelfResponse::success('冻结成功','b_User_activatedUsers');
        }
        return SelfResponse::error($user_center->getErrorMsg('冻结失败,请稍后再试！'));
    }

    /**
     * @title 解冻会员
     * @param $id
     * @return SelfResponse
     */
    public function unfreezeUser($id)
    {
        $user_center = new UserCenter();
        if($user_center->unfreeze($id)){
            return SelfResponse::success('解冻成功','b_User_activatedUsers');
        }
        return SelfResponse::error($user_center->getErrorMsg('解冻失败,请稍后再试！'));
    }

    /**
     * @title 会员详细信息
     * @param $id
     * @return View
     */
    public function infoUser($id)
    {
        $info = UserBaseModel::find($id);
        if(!$info->wallet){
            $info->wallet()->save(new UserWalletModel(['user_number'=>$info->user_number,'status'=>1]));
            $info->refresh();
        }
        return view('backend::user.info_user',[
           'info'=>$info,
            'currencies'=>get_currency(),
            'page_title'=>$info->real_name.'的详细信息'
        ]);
    }


    /**
     * @title 删除会员
     * @param Request $request
     * @return SelfResponse
     */
    public function deleteUser(Request $request)
    {
        $user_ids = $request->input('user_id');
        $user_ids = array_filter(is_array($user_ids)?$user_ids:str2arr($user_ids));
        if(!$user_ids){
            return SelfResponse::error('请选择要操作的数据');
        }
        //for2031
        $has_count_tj=UserBaseModel::where('referrer_id',$user_ids)->count();
        if($has_count_tj>0){
            return SelfResponse::error('该会员推荐有人');
        }
        $has_count_tj=UserBaseModel::where('jiedian_id',$user_ids)->count();
        if($has_count_tj>0){
            return SelfResponse::error('该会员节点有人');
        }
        $info=UserBaseModel::where('member_id',$user_ids)->first();

        if(UserBaseModel::whereIn('member_id',$user_ids)->delete()){
            UserBaseModel::where('member_id',$info->jiedian_id)->decrement('num_zj');
            UserAuthModel::init()->whereIn('member_id',$user_ids)->delete();
            UserInfoModel::init()->whereIn('member_id',$user_ids)->delete();
            UserWalletModel::init()->whereIn('member_id',$user_ids)->delete();
            return SelfResponse::success('删除会员成功','b_User_activatedUsers');
        }
        return SelfResponse::error('删除会员失败');
    }

    /**
     * @title 审核实名认证
     * @param $user_id
     * @return SelfResponse
     */
    public function agreeRealName($user_id)
    {
        $info = UserBaseModel::find($user_id);
        if(!$info || $info->is_real_name>=1){
            return SelfResponse::error('会员不存在或已通过实名认证');
        }
        $info->is_real_name = 1;
        if(!$info->save()){
            return SelfResponse::error('认证失败,请稍后再试');
        }
        return SelfResponse::success('认证成功',['b_User_infoUser',['id'=>$user_id]]);
    }

    /**
     * @title 修改会员身份 运营中心  合伙人
     * @param $user_id
     * @return SelfResponse
     */
    public function ChangeUserIdentity(Request $request,$user_id)
    {
        $info = UserBaseModel::init()->find($user_id);
        $value = $request->input('value');
        $type = $request->input('type');
        if ($type == 1) {
            $field = 'is_partner';
            if ($value == 0) {
                $info->$field = 1;
                if ($info->reg_type < 4) {
                    $info->reg_type = 4;
                }
                $typeText = "设置合伙人身份";
            } else {
                $info->$field = 0;
                $typeText = "取消合伙人身份";
            }
        } else {
            $field = 'is_bill';
            if ($value == 0) {
                $info->$field = 1;
                $typeText = "设置运营中心";
            } else {
                $info->$field = 0;
                $typeText = "取消运营中心";
            }
        }

        if(!$info->save()){
            return SelfResponse::error($typeText.'失败,请稍后再试');
        }
        return SelfResponse::success($typeText.'成功!');

    }

    /**
     * @title 关系图谱
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function relationTree(Request $request)
    {
        $user = $request->input('user', null);
        $root_id = 0;
        $userModel = UserBaseModel::with('children');
        if ($user) {
            $userModel = $userModel->where('user_number', $user);
            $post_info =  $userModel->where('user_number',$user)->first();
            $tdeep = $post_info->tdeep;
            $root_id = $post_info->member_id ;
        } else {
            $userModel = $userModel->where('referrer_id', $root_id);
            $tdeep = 0;
        }
        $root = $userModel->get()->toArray();

        $info = format_userTree($root,$tdeep);

        return $this->render('user.relation_tree', [
            'page_title' => '推荐图谱',
            'root' => json_encode($info),
            'root_id' => $root_id,
            'current_op' => 'tree',
        ]);
    }

    /**
     * @title 节点图谱
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function jiedianTree(Request $request)
    {
        $user = $request->input('user', null);
        $root_id = 0;
        $userModel = UserBaseModel::with('jiedianchildren');
        if ($user) {
            $userModel = $userModel->where('user_number', $user);
            $post_info =  $userModel->where('user_number',$user)->first();
            $jdeep = $post_info->jdeep;
            $root_id = $post_info->member_id ;
        } else {
            $userModel = $userModel->where('jiedian_id', $root_id);
            $jdeep = 0;
        }
        $root = $userModel->get()->toArray();

        $info = format_jiedianTree($root,$jdeep);

        return $this->render('user.jiedian_tree', [
            'page_title' => '节点图谱',
            'root' => json_encode($info),
            'root_id' => $root_id,
            'current_op' => 'tree',
        ]);
    }

    public function orgchat(Request $request)
    {
        $username = $request->input('user', null);
        if($username){
            $node_info=UserBaseModel::where('user_number',$username)->first();
        }else{
            $node_info=UserBaseModel::where('member_id',1)->first();
        }
        if(!$node_info){
            return $this->render('user.orgchat', [
                'page_title' => '节点图谱',
                'datascource'=>''
            ]);
        }
        $datascource['id']=strval($node_info->member_id);//这里要用字符串
        $datascource['name']=$node_info->user_number;
        $datascource['title']=$node_info->real_name;
        if($node_info->num_zj>0){
            $datascource['relationship']="001";
        }else{
            $datascource['relationship']="000";
        }
        $datascource_json=json_encode($datascource);
        return $this->render('user.orgchat', [
            'page_title' => '节点图谱',
            'datascource'=>$datascource_json
        ]);
    }
    public function nodechildren($nid=null){
        $res=[];
        $children_list=UserBaseModel::where('jiedian_id',$nid)->orderBy('leftright','asc')->get();
        foreach ($children_list as $clv){
            $datascource['id']=strval($clv->member_id);//这里要用字符串
            $datascource['name']=$clv->user_number;
            $datascource['title']=$clv->real_name;
            if($clv->num_zj>0){
                $datascource['relationship']="001";
            }else{
                $datascource['relationship']="000";
            }
            $res['children'][]=$datascource;
        }
        return $res;
    }

    public function asyncGetChildren(Request $request)
    {
        $user_id = $request->input('nodeId');
        $root_id = $request->get('root_id');
        $tdeep =  UserBaseModel:: where('member_id',$root_id)->value('tdeep');
        $root = UserBaseModel::with('children')->where('referrer_id', $user_id)->get()->toArray();
        $info = format_userTree($root,$tdeep);
        return response()->json([
            'status' => ["code" => 1, "message" => '加载成功'],
            'data' => $info
        ]);
    }
    public function asyncGetJiedianChildren(Request $request)
    {
        $user_id = $request->input('nodeId');
        $root_id = $request->get('root_id');
        $jdeep =  UserBaseModel:: where('member_id',$root_id)->value('jdeep');
        $root = UserBaseModel::with('jiedianchildren')->where('jiedian_id', $user_id)->get()->toArray();
        $info = format_jiedianTree($root,$jdeep);
        return response()->json([
            'status' => ["code" => 1, "message" => '加载成功'],
            'data' => $info
        ]);
    }

    /**
     * @title 调整静态积分
     * @param $user_id
     * @return SelfResponse
     */
    public function updateStaticPoint(Request $request,$user_id){
        $validatedData = $request->validate([
            'correct_number' => 'required|numeric',
        ],[
            'required'=>':attribute不能为空',
            'numeric'=>':attribute只能为数值',
        ],[
            'correct_number'=>'校正数量',
        ]);
        $user_info = UserBaseModel::where('member_id',$user_id)->first();
        if(!$user_info){
            return SelfResponse::error('会员不存在!');
        }
        $type = $request->input('type') ;
        if($type == 1){
            $field = "show_share_num";
            $typeText = "个人销售" ;
        }else{
            $field = "show_share_team_num";
            $typeText = "团队销售" ;
        }
        $money = abs($validatedData['correct_number']);
        if($validatedData['correct_number'] >0){
            $res = UserBaseModel::where('member_id',$user_id)->increment($field,$money);
            $type_msg = '增加';
            $correct_type = 1;
        }else{
            $res = UserBaseModel::where('member_id',$user_id)->decrement($field,$money);
            $type_msg = '扣除';
            $correct_type = 0;
        }
        if(!$res){
            return SelfResponse::error($type_msg.$typeText.'失败!');
        }

//        $remark = $type_msg.$money.'静态积分';
//        LogsAdminModel::init()->setOptTitle('校正账户')->setRemark($remark)
//            ->setOptData([
//                'user_id'=>$user_id,
//                'user_number'=>$user_info['user_number'],
//                'field'=>$field,
//                'inout'=>$correct_type,
//                'money'=>$money
//            ])->recording();

        return SelfResponse::success($type_msg.$typeText.'成功!');

    }



    /**
     * @title 会员伞下每日新增信息
     * @param $id
     * @return SelfResponse
     */
    public function DayAddUserInfo(Request $request,$id){

        $info = UserBaseModel::init()->find($id);

        $search = Search::make($request)->bindModel(new UserAchievementModel())
            ->time('created_at','统计时间')
            ->bindSearchData();

        $model = $search->where();

        $list = $model->where('user_id',$id)->orderBy('created_at','desc')->paginate($this->getPerPageNum());

        return view('backend::user.day_users_add',[
            'page_title'=>$info->real_name.'伞下每日新增信息',
            'list'=>$list,
            'user_id'=>$info->member_id,
            'search_tpl'=>$search
        ]);

    }

    /**
     * @title 访问前台
     * @param $user_id
     * @return SelfResponse
     */
    public function visitFrontend($user_id)
    {
        $info = UserBaseModel::find($user_id);
        if(!$info){
            return SelfResponse::error('会员不存在');
        }
        $data['user_number'] = $info->user_number;
        $data['login_pwd'] = $info->auth->login_pwd;
        $data['time'] = time();
        $data['ip'] = md5(get_client_ip(1));

        $url = config("website.home_url").'/verify_login';
        if(!preg_match('/(http:\/\/)|(https:\/\/)/i', $url)){
            $url = 'http://'.$url;
        }
        $str = json_encode($data);
        $encrypt = SelfEncrypt::encrypt($str,config('encrypt.access_token'));

        echo "<form style='display:none;' id='form1' name='form1' method='post' action='{$url}'>".
            "<input name='lginfo' type='hidden' value='{$encrypt}' /></form>".
            "<script type='text/javascript'>document.form1.submit();</script>";
    }
}